from django.views.generic import ListView, DetailView
from brp_app.models import Book
from django.http import HttpResponseRedirect, HttpResponse

class BookListView(ListView):
    model = Book

    def get_context_data(self, **kwargs):
        context = super(BookListView, self).get_context_data(**kwargs)
        context['not_read'] = Book.objects.filter(status='NOT READ').count()
        context['in_progress'] = Book.objects.filter(status='IN PROGRESS').count()
        context['finished'] = Book.objects.filter(status='FINISHED').count()
        return context


class BookDetailView(DetailView):
    model = Book


def book_save(request, book_id):
    if request.method == 'POST':
        checked_entries = request.POST.getlist('read')
        book = Book.objects.get(id=book_id)
        for entry in book.entries.all():
            if entry.read and str(entry.id) not in checked_entries:
                entry.read = False
                entry.save()
            elif not entry.read and str(entry.id) in checked_entries:
                entry.read = True
                entry.save()
        book.save()
    return HttpResponseRedirect('/brp/book/%s/' % book_id)